import { clearLoginInfo, Base64 } from './index';

// var baseurl = 'http://192.168.5.25:8763/crmApi';/*192.168.1.7:8766*/
// var baseurl ='https://api.yiliit.com/crmApi';
var baseurl = 'https://192.168.5.33/crmApi';
// var baseurl = 'http://24795tz835.zicp.vip/crmApi';
// var baseurl = 'http://api.yiliit.com/crmApi';

var imgBackUrl = 'https://one-stand.oss-cn-shanghai.aliyuncs.com/' ;
let base64 = new Base64();

function gettoken () {

  return wx.getStorageSync('token') || ''
}
function getcookie() {
  // var cookie = wx.getStorageSync('cookies') || '';
  return wx.getStorageSync('cookies') || ''
}

export function POST (request, method , service ,str) {

  // wx.setStorageSync('token','ulbrvtpvyt');

  var contentType = '' ,
    url = '' ;
  if(method == 'json'){
    contentType = 'multipart/form-data' ;
    url = baseurl  + service;
  }else{
    contentType = 'application/x-www-form-urlencoded' ;
    url = baseurl + service;
  }

  let data = request;

  if (Object.keys(request).length) {
    data  = {
      data: base64.encode(JSON.stringify(request)),
    }
  }


  return new Promise((resolve, reject) => {
    wx.request({
      url: url ,
      data: data,
      method: 'POST',
      header: {
        'content-type': contentType,
        'token' : gettoken() ,
        'cookie' : 'PHPSESSID='+getcookie() ,
        'companyKey': 'one-stand',
        'time': Date.now(),
      },
      success: function (data) {
        /*
        *   SUCCESS(200,"成功"),
            ERROR(500,"系统异常"),
            FAULT_TOLERANT(501,"容错"),
            FAIL(201,"操作失败"),
            NO_LOGIN(401,"未登陆"),
            NO_ROLE(403,"无权限"),
            NO_PARAM(202,"参数缺失"),
            PARAM_CHECK(203,"参数校验失败"),
            NO_DATA(204,"无数据"),
            TEST(999999,"TEST")
        * */
        if(data.data.code == 200 || data.data.code == 209 || data.data.code == 204){
          resolve(data.data.data, data.data.code);
        }else if(data.data.code == 401){
          clearLoginInfo();
          wx.showToast({
            title: '请登录',
            duration: 2000,
            icon: 'none'
          });
          setTimeout(function () {
            var url = '../wxLogin/main';
            wx.redirectTo({url: url});
          },1000)

        }else if (data.data.code == 403){
          reject(data.data);
        }else{
          reject(data.data);
          // console.log('data--',data);
          wx.showToast({
            title: data.data.message ||  '服务器繁忙',
            duration: 2000,
            icon: 'none'
          })
        }
      },
      fail: function (err) {
        reject(err);
        // wx.showModal({
        //   title: '提示',
        //   content: JSON.stringify(err),
        //   success (res) {
        //     if (res.confirm) {
        //       console.log('用户点击确定')
        //     } else if (res.cancel) {
        //       console.log('用户点击取消')
        //     }
        //   }
        // })
      }
    })
  })
}

export function GET (request, successed, service) {
  return new Promise((resolve, reject) => {
    wx.request({
      header: {
        'content-type': 'application/json',// 默认值
        'token' : gettoken(),
        'cookie' : 'PHPSESSID='+getcookie() ,
      },
      url: baseurl + service  ,
      data: request,
      success: function (data) {
        if(data.data.code == 200 || data.data.code == 209 ){
          resolve(data.data.data)
        } else if(data.data.code == 401){
          clearLoginInfo();
          wx.showToast({
            title: '请登录',
            duration: 2000,
            icon: 'none'
          });
          setTimeout(function () {
            var url = '../wxLogin/main';
            wx.redirectTo({url: url});
          },1000);
        } else{
          wx.showToast({
            title: data.data.msg ||  '服务器繁忙',
            duration: 2000,
            icon: 'none'
          })
        }
      },
      fail: function (err) {
        reject(err);
        wx.showToast({
          title: '服务器繁忙',
          duration: 2000,
          icon: 'none'
        })
      }
    })
  })
}

export function DELETE (request, successed, service) {
  return new Promise((resolve, reject) => {
    wx.request({
      header: {
        'content-type': 'application/x-www-form-urlencoded',// 默认值
        'token' : gettoken(),
        'cookie' : 'PHPSESSID='+getcookie() ,
      },
      method: 'DELETE',
      url: baseurl + service,
      data: request,
      success: function (data) {
        if(data.data.code == 200 || data.data.code == 209 ){
          resolve(data.data.data)
        }else{
          wx.showToast({
            title: data.data.msg ||  '服务器繁忙',
            duration: 2000,
            icon: 'none'
          })
        }
      },
      fail: function (err) {
        reject(err);
        wx.showToast({
          title: '服务器繁忙',
          duration: 2000,
          icon: 'none'
        })
      }
    })
  })
}


export function UploadImage (imgPath, method , service) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: 'https://api.yiliit.com/file/uploadObjectOSS', //
      // https://api.yiliit.com/file/uploadObjectOSS
      //https://192.168.1.130/file/uploadObjectOSS
      filePath: imgPath,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data'
      },
      success(data) {
        if(data.statusCode == 200 || data.data.code == 209 ){
          resolve(data.data)
        }else{
          wx.showToast({
            title: data.data.msg ||  '服务器繁忙',
            duration: 2000,
            icon: 'none'
          })
        }
      },
      fail(err){
        console.log(err) ;
        reject(err);
        wx.showToast({
          title: '服务器繁忙',
          duration: 2000,
          icon: 'none'
        })
      }
    })
  })
}


export function checkCollect (request , service) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseurl + '/personal/getIsCollection' ,
      data: request,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token' : gettoken() ,
      },
      success: function (data) {
        /*
        *   SUCCESS(200,"成功"),
            ERROR(500,"系统异常"),
            FAULT_TOLERANT(501,"容错"),
            FAIL(201,"操作失败"),
            NO_LOGIN(401,"未登陆"),
            NO_ROLE(403,"无权限"),
            NO_PARAM(202,"参数缺失"),
            PARAM_CHECK(203,"参数校验失败"),
            NO_DATA(204,"无数据"),
            TEST(999999,"TEST")
        * */
        if(data.data.code == 200 || data.data.code == 209 ){

          if(data.data.data){
            if(data.data.data){
              resolve({status:true,collectionId:data.data.data.collectionId})
            }else{
              resolve({status:false} )
            }
          }else{
            resolve({status:false} );
          }

        }else if(data.data.code == 401){
          wx.showToast({
            title: '请登录',
            duration: 2000,
            icon: 'none'
          });
          setTimeout(function () {
            var url = '../cardCase/main';
            wx.redirectTo({url: url});
          },1000)
        }else{
          resolve({status:false} );
          // console.log('data--',data);
          /*  wx.showToast({
                title: data.data.message ||  '服务器繁忙',
                duration: 2000,
                icon: 'none'
            })*/
        }
      },
      fail: function (err) {
        reject(false);
        wx.showModal({
          title: '提示',
          content: JSON.stringify(err),
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  })
}

export function changeCollect (request , service) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseurl + service ,
      data: request,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token' : gettoken() ,
      },
      success: function (data) {
        /*
        *   SUCCESS(200,"成功"),
            ERROR(500,"系统异常"),
            FAULT_TOLERANT(501,"容错"),
            FAIL(201,"操作失败"),
            NO_LOGIN(401,"未登陆"),
            NO_ROLE(403,"无权限"),
            NO_PARAM(202,"参数缺失"),
            PARAM_CHECK(203,"参数校验失败"),
            NO_DATA(204,"无数据"),
            TEST(999999,"TEST")
        * */
        if(data.data.code == 200 || data.data.code == 209 ){

          resolve(true);

        }else if(data.data.code == 401){
          wx.showToast({
            title: '请登录',
            duration: 2000,
            icon: 'none'
          });
          setTimeout(function () {
            var url = '../cardCase/main';
            wx.redirectTo({url: url});
          },1500)
        }else{
          resolve(false );
          // console.log('data--',data);
          wx.showToast({
            title: data.data.message ||  '服务器繁忙',
            duration: 2000,
            icon: 'none'
          })
        }
      },
      fail: function (err) {
        resolve(true );
        wx.showModal({
          title: '提示',
          content: JSON.stringify(err),
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  })
}


export function ToPay (request , service) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseurl + '/orders/goPay' ,
      data: request,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token' : gettoken() ,
      },
      success: function (data) {
        /*
        *   SUCCESS(200,"成功"),
            ERROR(500,"系统异常"),
            FAULT_TOLERANT(501,"容错"),
            FAIL(201,"操作失败"),
            NO_LOGIN(401,"未登陆"),
            NO_ROLE(403,"无权限"),
            NO_PARAM(202,"参数缺失"),
            PARAM_CHECK(203,"参数校验失败"),
            NO_DATA(204,"无数据"),
            TEST(999999,"TEST")
        * */
        if(data.data.code == 200 || data.data.code == 209 ){

          //data.data.data
          if(data.data.data){
            let _data = data.data.data ;
            wx.requestPayment({
              timeStamp: _data.timeStamp,
              nonceStr: _data.nonce_str,
              package: 'prepay_id=' + _data.prepay_id,
              signType: 'MD5',
              paySign: _data.paySign,
              success(res) {
                console.log(res);
                wx.showToast({
                  title: '支付成功',
                  icon: 'success'
                });
                resolve(true);
                setTimeout(() => {
                  let url = '../orderLists/main';
                  wx.navigateTo({url: url});
                }, 800)
              },
              fail(err) {
                console.log(err);
                reject(false);
                if (err.errMsg === 'requestPayment:fail cancel') {
                  wx.showToast({
                    title: '支付已取消',
                    icon: 'none'
                  })
                } else {
                  wx.showToast({
                    title: '支付失败',
                    icon: 'none'
                  })
                }

              }
            })
          }else{
            reject(false);
          }


        }else if(data.data.code == 401){
          reject(false);
          wx.showToast({
            title: '请登录',
            duration: 2000,
            icon: 'none'
          });
          setTimeout(function () {
            var url = '../cardCase/main';
            wx.redirectTo({url: url});
          },1500)

        }else{
          resolve(false );
          // console.log('data--',data);
          wx.showToast({
            title: data.data.message ||  '服务器繁忙',
            duration: 2000,
            icon: 'none'
          })
        }
      },
      fail: function (err) {
        resolve(false );
        wx.showModal({
          title: '提示',
          content: JSON.stringify(err),
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  })
}



export default {
  POST,
  GET ,
  DELETE,
  UploadImage ,
  imgBackUrl ,
  checkCollect ,
  changeCollect ,
  ToPay
}


